package com.firebird.app.reader.pdf.activity

import android.Manifest
import android.annotation.SuppressLint
import android.app.AlertDialog
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.Color
import android.graphics.Paint
import android.graphics.pdf.PdfDocument
import android.graphics.pdf.PdfRenderer
import android.net.Uri
import android.os.Bundle
import android.os.ParcelFileDescriptor
import android.view.View
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.firebird.app.reader.R
import ja.burhanrashid52.photoeditor.OnSaveBitmap
import ja.burhanrashid52.photoeditor.PhotoEditor
import ja.burhanrashid52.photoeditor.PhotoEditorView
import me.panpf.sketch.SketchImageView
import java.io.File
import java.io.FileOutputStream
import java.io.IOException

import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity(), View.OnClickListener {
    private var mFileDescriptor // File descriptor of the PDF.
            : ParcelFileDescriptor? = null
    private var mPdfRenderer: PdfRenderer? = null
    private var mCurrentPage //Page that is currently shown on the screen.
            : PdfRenderer.Page? = null
    private var mPhotoEditor: PhotoEditor? = null
    private var pdfShowIv //显示PDF的区域
            : PhotoEditorView? = null
    private var previousBtn //前一页PDF
            : ImageButton? = null
    private var nextBtn //后一页PDF
            : ImageButton? = null
    private var clearBtn //清除按钮
            : ImageButton? = null
    private var linkBtn //跳转网站按钮
            : ImageButton? = null
    private var saveBtn //保存按钮
            : ImageButton? = null
    private var firstPage //第一页
            : ImageButton? = null
    private var lastPage //最后一页
            : ImageButton? = null
    private var movieBtn //跳转视频链接
            : ImageButton? = null
    private var backBtn //后退按钮
            : ImageButton? = null
    private var currentIndex = 0
    //private var pDialog: ProgressBar? = null
    private var mProgressBar: ProgressBar? = null
    private var currentBitmap //当前图片的bitmap
            : Bitmap? = null
    private var sketchImageView: SketchImageView? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        permission()
        currentIndex = 0
        initView()
        initImageEditor()
    }

    /**
     * 初始化控件
     */
    private fun initView() {
        pdfShowIv = findViewById<View>(R.id.am_pdf_image) as PhotoEditorView
        sketchImageView = findViewById<View>(R.id.am_pdf_zoom_iv) as SketchImageView
        pdfShowIv!!.source.scaleType = ImageView.ScaleType.FIT_CENTER
        previousBtn = findViewById<View>(R.id.am_previous_btn) as ImageButton
        nextBtn = findViewById<View>(R.id.am_next_btn) as ImageButton
        clearBtn = findViewById<View>(R.id.am_init_btn) as ImageButton
        linkBtn = findViewById<View>(R.id.am_link_btn) as ImageButton
        saveBtn = findViewById<View>(R.id.am_save_btn) as ImageButton
        firstPage = findViewById<View>(R.id.am_first_page_btn) as ImageButton
        lastPage = findViewById<View>(R.id.am_latest_page_btn) as ImageButton
        movieBtn = findViewById<View>(R.id.am_movie_btn) as ImageButton
        backBtn = findViewById<View>(R.id.am_back_btn) as ImageButton
        previousBtn!!.setOnClickListener(this)
        nextBtn!!.setOnClickListener(this)
        clearBtn!!.setOnClickListener(this)
        linkBtn!!.setOnClickListener(this)
        saveBtn!!.setOnClickListener(this)
        firstPage!!.setOnClickListener(this)
        lastPage!!.setOnClickListener(this)
        movieBtn!!.setOnClickListener(this)
        backBtn!!.setOnClickListener(this)
    }

    /**
     * 初始化图片编辑器
     */
    private fun initImageEditor() {
        mPhotoEditor = PhotoEditor.Builder(this as Context, pdfShowIv)
               .setPinchTextScalable(false)
               .build()
        mPhotoEditor?.setBrushDrawingMode(true)
        mPhotoEditor?.setBrushSize(10f)
        mPhotoEditor?.setBrushColor(Color.BLACK)
    }

    override fun onStart() {
        super.onStart()
        openPdf()
    }

    /**
     * Sets up a [android.graphics.pdf.PdfRenderer] and related resources.
     */
    @Throws(IOException::class)
    private fun openRenderer(context: Context) { // In this sample, we read a PDF from the assets directory.
        val file = File(context.cacheDir, FILENAME)
        if (!file.exists()) { // Since PdfRenderer cannot handle the compressed asset file directly, we copy it into
// the cache directory.
            val asset = context.assets.open(FILENAME)
            val output = FileOutputStream(file)
            val buffer = ByteArray(1024)
            var size: Int
            while (asset.read(buffer).also { size = it } != -1) {
                output.write(buffer, 0, size)
            }
            asset.close()
            output.close()
        }
        mFileDescriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY)
        // This is the PdfRenderer we use to render the PDF.
        if (mFileDescriptor != null) {
            mPdfRenderer = PdfRenderer(mFileDescriptor!!)
        }
    }

    /**
     * Shows the specified page of PDF to the screen.
     *
     * @param index The page index.
     */
    private fun showPage(index: Int) {
        if (mPdfRenderer!!.pageCount <= index) {
            return
        }
        // Make sure to close the current page before opening another one.
        if (null != mCurrentPage) {
            try {
                mCurrentPage!!.close()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        // Use `openPage` to open a specific page in PDF.
        mCurrentPage = mPdfRenderer!!.openPage(index)
        // Important: the destination bitmap must be ARGB (not RGB).
        currentBitmap = Bitmap.createBitmap(mCurrentPage!!.width, mCurrentPage!!.height,
                Bitmap.Config.ARGB_8888)
        val imgSrcParam = RelativeLayout.LayoutParams(
                mCurrentPage!!.width, mCurrentPage!!.height)
        imgSrcParam.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE)
        pdfShowIv!!.layoutParams = imgSrcParam
        // Here, we render the page onto the Bitmap.
// To render a portion of the page, use the second and third parameter. Pass nulls to get
// the default result.
// Pass either RENDER_MODE_FOR_DISPLAY or RENDER_MODE_FOR_PRINT for the last parameter.
        mCurrentPage?.render(currentBitmap!!, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY)
        // We are ready to show the Bitmap to user.
        pdfShowIv!!.source.setImageBitmap(currentBitmap)
        updateUi()
    }

    /**
     * Updates the state of 2 control buttons in response to the current page index.
     */
    private fun updateUi() {
        currentIndex = mCurrentPage!!.index
        val pageCount = mPdfRenderer!!.pageCount
        previousBtn!!.isEnabled = 0 != currentIndex
        nextBtn!!.isEnabled = currentIndex + 1 < pageCount
    }

    override fun onClick(view: View) {
        when (view.id) {
            R.id.am_previous_btn -> {
                //                // Move to the previous page
                showPage(mCurrentPage!!.index - 1)
                mPhotoEditor!!.clearAllViews()
            }
            R.id.am_next_btn -> {
                //                pdfShowIv.setVisibility(View.GONE);
//                sketchImageView.setImageBitmap(currentBitmap);
//                sketchImageView.setZoomEnabled(true);
//                sketchImageView.setVisibility(View.VISIBLE);
// Move to the next page
                showPage(mCurrentPage!!.index + 1)
                mPhotoEditor!!.clearAllViews()
            }
            R.id.am_init_btn -> {
                mPhotoEditor!!.clearAllViews()
            }
            R.id.am_link_btn -> {
                val intent = Intent()
                intent.action = "android.intent.action.VIEW"
                val content_url = Uri.parse("https://www.sinwanet.co.jp/")
                intent.data = content_url
                startActivity(intent)
            }
            R.id.am_save_btn -> {
                if (permission()) { //如果有SD卡的许可才能进行操作
                    mProgressBar = ProgressBar(this, null, android.R.attr.progressBarStyleLarge)
                    //RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(100, 100);
                    //params.addRule(RelativeLayout.CENTER_IN_PARENT);
                    //layout.addView(progressBar, params)
                    mProgressBar!!.setVisibility(View.VISIBLE)
                   // pDialog = ProgressBar.show(this, ""
                         //   , getString(R.string.common_loading), false, false)
                    saveAsPdfFile()
                }
            }
            R.id.am_first_page_btn -> {
                showPage(0)
                mPhotoEditor!!.clearAllViews()
            }
            R.id.am_latest_page_btn -> {
                showPage(mPdfRenderer!!.pageCount - 1)
                mPhotoEditor!!.clearAllViews()
            }
            R.id.am_movie_btn -> {
                val intent = Intent()
                intent.action = "android.intent.action.VIEW"
                val content_url = Uri.parse("https://youtu.be/yZbnUQPr38Y")
                intent.data = content_url
                startActivity(intent)
            }
            R.id.am_back_btn -> {
                finish()
            }
        }
    }

    private fun saveAsPdfFile() { //        String sdPath = FileUtils.getSDPath();
//        if (sdPath == null) {//没有SD卡不能保存，可以添加提示
//            return;
//        }
        checkSdFolder()
    }

    @SuppressLint("MissingPermission")
    private fun checkSdFolder() {
        mPhotoEditor!!.saveAsBitmap(object : OnSaveBitmap {
            override fun onBitmapReady(saveBitmap: Bitmap) {
                saveAsPdf(saveBitmap)
            }

            override fun onFailure(e: Exception) {}
        })
    }

    private fun saveAsPdf(saveBitmap: Bitmap) { // create a new document
        val document = PdfDocument()
        if (null != mCurrentPage) {
            mCurrentPage!!.close()
        }
        // crate a page description
        for (i in 0 until mPdfRenderer!!.pageCount) {
            if (i == currentIndex) {
                val pageInfo = PdfDocument.PageInfo.Builder(saveBitmap.width
                        , saveBitmap.height, 0).create()
                createPdfPage(document, pageInfo, saveBitmap)
            } else {
                mCurrentPage = mPdfRenderer!!.openPage(i)
                val pageInfo = PdfDocument.PageInfo.Builder(mCurrentPage!!.width
                        , mCurrentPage!!.height, 0).create()
                val bitmap = Bitmap.createBitmap(mCurrentPage!!.width, mCurrentPage!!.height,
                        Bitmap.Config.ARGB_8888)
                // Here, we render the page onto the Bitmap.
// To render a portion of the page, use the second and third parameter. Pass nulls to get
// the default result.
// Pass either RENDER_MODE_FOR_DISPLAY or RENDER_MODE_FOR_PRINT for the last parameter.
                mCurrentPage?.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY)
                if (null != mCurrentPage) {
                    mCurrentPage!!.close()
                }
                createPdfPage(document, pageInfo, bitmap)
            }
        }
        // 输出到文件
        try {
            val file=File(cacheDir, FILENAME)
            val outputStream = FileOutputStream(file)
            document.writeTo(outputStream)
        } catch (e: IOException) {
            e.printStackTrace()
        }
        openPdf()
        if (mProgressBar != null) {
           // mProgressBar!!.cancel()
            mProgressBar?.setVisibility(View.INVISIBLE)
        }
        AlertDialog.Builder(this)
                .setMessage(R.string.am_commit_success)
                .setIcon(R.mipmap.ic_launcher)
                .setPositiveButton(R.string.common_ok_jp) { dialogInterface,_ ->
                //.setPositiveButton(R.string.common_ok_jp) {it ->
                    //添加"Yes"按钮
                    dialogInterface.cancel()
                   // it.cancel()
                }
                .create().show()
    }

    private fun openPdf() {
        try {
            /*val fileText: String = applicationContext.assets.open("test.txt").bufferedReader().use {
                it.readText()
            }
            println(fileText)

            val file = File(application.cacheDir, FILENAME)
            if (!file.exists()) {
               // application.assets.open(FILENAME).use { asset ->
                applicationContext.assets.open(FILENAME).use { asset ->
                    file.writeBytes(asset.readBytes())
                }
            }*/
            openRenderer(this)
            showPage(currentIndex)
        } catch (e: IOException) {
            e.printStackTrace()
            Toast.makeText(this, "Error! " + e.message, Toast.LENGTH_SHORT).show()
        }
    }

    private fun createPdfPage(document: PdfDocument, pageInfo: PdfDocument.PageInfo, saveBitmap: Bitmap) { // start a page
        val page = document.startPage(pageInfo)
        val canvas = page.canvas
        val mPaint = Paint()
        canvas.drawBitmap(saveBitmap, 0f, 0f, mPaint)
        document.finishPage(page)
    }

    /**
     * 获取权限
     *
     * @return
     */
    private fun permission(): Boolean
    {
        val hasWriteStoragePermission = ContextCompat.checkSelfPermission(application, Manifest.permission.WRITE_EXTERNAL_STORAGE)
        if (hasWriteStoragePermission != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), CODE_REQUEST_PERMISSION)
            return false
        }
        return true
    }

    companion object {
        private const val CODE_REQUEST_PERMISSION = 0x10
        private const val FILENAME = "kotlin-reference-chinese.pdf" //测试用的pdf文件
    }
}